package jfuzzyprincepless.negotiation.services.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import jfuzzyprincepless.negotiation.services.IService;

import laboratoryQ.computation.BaseUtils;

public class ServiceRegistry {
	private Map<Class<? extends IService>, Object> interf2service =
		new HashMap<Class<? extends IService>, Object>();

	@SuppressWarnings("unchecked")
	public <ServT> ServT getService(Class<ServT> clazz) {
		return (ServT)interf2service.get(clazz);
	}

	public void registerService(IService service) {
		Class<?> clazz = service.getClass();
		for (Class<?> interf : BaseUtils.extractAllInterfaces(clazz)) {
			privateRegisterService(interf, service);
		}
	}
	
	public <ServT extends IService> void registerService(
		Class<ServT> clazz,
		ServT service
	) {
		privateRegisterService(clazz, service);
	}

	@SuppressWarnings("unchecked")
	private void privateRegisterService(Class<?> interf, Object service) {
		if (!interf.isInstance(service)) {
			throw new IllegalArgumentException(
				"service was expected to be instanceof interf"
			);
		}
		if (IService.class.isAssignableFrom(interf)) {
			interf2service.put((Class<? extends IService>) interf, service);
		}
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (Entry<Class<? extends IService>, Object> entry : interf2service.entrySet()) {
			sb
				.append(entry.getKey())
				.append("->")
				.append(entry.getValue())
				.append("\n");
		}
		return sb.toString();
	}
}
